package ch18.v3.Dao;

import ch18.v3.model.Student;
import ch18.v3.util.FileUtil;

import java.util.ArrayList;
import java.util.List;

public class StudentManagerDao {

    private List<Student> studentData;


    public StudentManagerDao() {
        studentData = FileUtil.loadStudents();
        if (studentData == null) {
            studentData = new ArrayList<>();
        }
    }

    public boolean add(Student student) {
        if (student == null || student.getStuNo() == null) {
            return false;
        }
        studentData.add(student);
        saveData();
        return true;
    }

    private void saveData() {
        FileUtil.saveStudents(studentData);
    }

    /*public StudentManagerDao() {
        studentData = FileUtil.loadStudents();
    }

    public boolean add(Student student) {
        if (student == null || student.getStuNo() == null) {
            return false;
        }
        studentData.add(student);
        saveData();
        return true;
    }*/

    public boolean delete(String stuNo) {
        if (stuNo == null) {
            return false;
        }
        boolean removed = studentData.removeIf(student -> stuNo.equals(student.getStuNo()));
        if (removed) {
            saveData();
        }
        return removed;
    }

    public boolean update(Student updatedStudent) {
        if (updatedStudent == null || updatedStudent.getStuNo() == null) {
            return false;
        }
        for (int i = 0; i < studentData.size(); i++) {
            if (updatedStudent.getStuNo().equals(studentData.get(i).getStuNo())) {
                studentData.set(i, updatedStudent);
                saveData();
                return true;
            }
        }
        return false;
    }

    public List<Student> queryLists() {
        return new ArrayList<>(studentData);
    }

    public Student query(String stuNo) {
        for (Student student : studentData) {
            if (stuNo.equals(student.getStuNo())) {
                return student;
            }
        }
        return null;
    }

    /*private void saveData() {
        FileUtil.saveStudents(studentData);
    }*/
}